import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/models/response/content_response.dart';
import 'package:sainbainu/common/models/response/group_list_response.dart';
import 'package:sainbainu/common/models/response/user_list_response.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/widget.dart';
import 'package:nested_scroll_view_plus/nested_scroll_view_plus.dart';

import 'index.dart';
import 'widgets/widgets.dart';

class GlobalSearchPage extends GetView<GlobalSearchController> {
  const GlobalSearchPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<GlobalSearchController>(
      builder: (_) {
        return KeyboardClose(
          child: Scaffold(
            appBar: AppBar(
              leading: GestureDetector(
                child: const Icon(Icons.arrow_back_ios_new_rounded),
                onTap: () => Get.back(),
              ),
              title: SearchInput(
                onClearTap: () => _.handleClearInput(),
                onDoneTap: (text) => _.handleInputSearch(text),
              ),
              titleSpacing: 0,
              actions: const [SizedBox(width: 20)],
              scrolledUnderElevation: 0,
            ),
            body: _buildBody(),
          ),
        );
      },
    );
  }

  /// 返回不同搜索页面
  Widget _buildBody() {
    return Obx(() {
      if (controller.state.pageType.value == PageType.searching) {
        return _buildSearchingPage();
      } else if (controller.state.pageType.value == PageType.result) {
        return _buildResultPage();
      } else {
        return const SizedBox.shrink();
      }
    });
  }

  /// 搜索面板页
  Widget _buildSearchingPage() {
    return Container(
      color: AppColors.nav,
      child: SearchPanel(
        onHistoryTap: (text) => controller.handleHistorySearch(text),
        onHistoryClearConfirmTap: () => controller.handleClearHistory(),
        onHistoryClearToggleTap: () => controller.handleHistoryClearToggle(),
        onHotTap: (text) => controller.handleHotSearch(text),
        onHotRefreshTap: () => controller.handleRefreshHot(),
      ),
    );
  }

  /// 搜索结果页
  Widget _buildResultPage() {
    return DefaultTabController(
      length: 3,
      initialIndex: controller.state.tabsIndex.value,
      child: NestedScrollViewPlus(
        overscrollBehavior: OverscrollBehavior.outer,
        headerSliverBuilder: (context, innerScrolled) {
          return [
            SliverAppBar(
              pinned: true,
              toolbarHeight: 0,
              bottom: TabBar(
                onTap: controller.handleTabChange,
                dividerHeight: 0,
                tabs: [
                  Tab(text: '帖子'.tr),
                  Tab(text: '小组'.tr),
                  Tab(text: '用户'.tr),
                ],
              ),
            )
          ];
        },
        body: EasyRefresh.builder(
          controller: controller.state.refreshController,
          onLoad: controller.onRichBottom,
          childBuilder: (context, physics) {
            return _buildTabsBody(physics);
          },
        ),
      ),
    );
  }

  /// 返回不同 tabs 页面
  Widget _buildTabsBody(ScrollPhysics physics) {
    return Obx(() {
      GlobalSearchState state = controller.state;

      Widget child;
      if (state.tabsIndex.value == 0) {
        child = _buildContentList(physics);
      } else if (state.tabsIndex.value == 1) {
        child = _buildGroupList(physics);
      } else if (state.tabsIndex.value == 2) {
        child = _buildUserList(physics);
      } else {
        child = const SizedBox.shrink();
      }
      return PageWrapper(
        showLoadingPage: state.fetchLoading.value,
        loadingText: '正在搜索...',
        child: child,
      );
    });
  }

  /// 内容列表
  Widget _buildContentList(ScrollPhysics physics) {
    return GetBuilder<GlobalSearchController>(
      id: 'search_list',
      builder: (_) {
        return PageWrapper(
          showLoadingPage: false,
          showResultPage: _.state.noteListResponse.rows.isEmpty,
          resultBtn: false,
          resultDesc: '暂无搜索结果',
          child: ListView.separated(
            physics: physics,
            itemCount: _.state.noteListResponse.rows.length,
            separatorBuilder: (context, index) {
              return const SizedBox(height: 10);
            },
            padding: const EdgeInsets.all(0),
            itemBuilder: (context, index) {
              ContentResponse item = _.state.noteListResponse.rows[index];
              return GestureDetector(
                onTap: () {
                  _.toContentDetailPage(item);
                },
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.only(
                    top: 20,
                    left: 20,
                    right: 20,
                    bottom: 5,
                  ),
                  child: UserInfoCell(
                    avatarHeroTag: '${item.uniqueTag}_${item.noteId}',
                    avatar: item.avatar,
                    name: item.customerName ?? '',
                    role: item.officialName,
                    showRoleAuth: item.officialFlag == 1,
                    groupName: item.groupName,
                    region: '${item.provinceName}${item.cityName}',
                    dateTime: item.createTime,
                    onUserTap: () {
                      _.toUserDetailPage(item.customerId);
                    },
                    onGroupTap: () {
                      _.toGroupDetailPage(item.groupId, null, null);
                    },
                    bottomChild: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (item.text != null && item.text!.isNotEmpty)
                          Padding(
                            padding: const EdgeInsets.only(top: 6),
                            child: ContentCardText(item.text!),
                          ),
                        ImageVideoGrid(
                          padding: const EdgeInsets.only(top: 12),
                          imageLinkList: item.image ?? [],
                          videoLink: item.videoCover,
                        ),
                        if (item.audio != null && item.audio!.isNotEmpty)
                          Padding(
                            padding: const EdgeInsets.only(top: 12),
                            child: AudioWaveWidget(
                              duration: item.audioDuration ?? 0,
                            ),
                          ),
                        IconNumRow(
                          giveFlag: item.giveFlag ?? 0,
                          giveNum: item.giveNum ?? 0,
                          collectionFlag: item.collectionFlag ?? 0,
                          collectionNum: item.collectionNum ?? 0,
                          visitNum: item.visitNum ?? 0,
                          commentNum: item.commentNum ?? 0,
                          shareNum: item.shareNum ?? 0,
                          onLikeTap: (isGive) =>
                              _.onGiveHandle(isGive, item.noteId),
                          onCollectionTap: (isGive) =>
                              _.onCollectionHandle(isGive, item.noteId),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 小组列表
  Widget _buildGroupList(ScrollPhysics physics) {
    return GetBuilder<GlobalSearchController>(
      id: 'search_list',
      builder: (_) {
        return PageWrapper(
          showLoadingPage: false,
          showResultPage: _.state.groupListResponse.rows.isEmpty,
          resultBtn: false,
          resultDesc: '未找到相关小组',
          child: ListView.separated(
            physics: physics,
            itemCount: _.state.groupListResponse.rows.length,
            separatorBuilder: (BuildContext context, int index) {
              return const SizedBox(height: 10);
            },
            padding: const EdgeInsets.all(0),
            itemBuilder: (BuildContext context, int index) {
              CroupItemResponse item = _.state.groupListResponse.rows[index];
              return GestureDetector(
                onTap: () => _.toGroupDetailPage(
                  item.groupId,
                  item.uniqueTag,
                  item.cover,
                ),
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    vertical: 10,
                    horizontal: 15,
                  ),
                  child: GroupItem(
                    item: item,
                    rightChild: GetBuilder<GlobalSearchController>(
                      id: 'join_btn',
                      builder: (_) => _buildFollowBtn(
                        text: item.joinFlag == 1 ? '已加入'.tr : '加入'.tr,
                        isOutline: item.joinFlag == 1,
                        onPressed: () => _.handleJoin(index),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 用户列表
  Widget _buildUserList(ScrollPhysics physics) {
    return GetBuilder<GlobalSearchController>(
      id: 'search_list',
      builder: (_) {
        return PageWrapper(
          showLoadingPage: false,
          showResultPage: _.state.userListResponse.rows.isEmpty,
          resultBtn: false,
          resultDesc: '未找到相关用户',
          child: ListView.separated(
            physics: physics,
            itemCount: _.state.userListResponse.rows.length,
            separatorBuilder: (BuildContext context, int index) {
              return const SizedBox(height: 1);
            },
            padding: const EdgeInsets.all(0),
            itemBuilder: (BuildContext context, int index) {
              UserItemResponse item = _.state.userListResponse.rows[index];

              String role = '';
              if (item.officialFlag == 1) {
                role = item.officialName ?? '';
              } else if (item.intro != null && item.intro!.isNotEmpty) {
                role = item.intro!;
              }

              return GestureDetector(
                onTap: () => _.toUserDetailPage(item.customerId),
                child: Container(
                  color: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    vertical: 10,
                    horizontal: 15,
                  ),
                  child: UserInfoCell(
                    avatar: item.avatar,
                    name: item.customerName ?? '',
                    role: role,
                    showRoleAuth: item.officialFlag == 1,
                    rightChild: GetBuilder<GlobalSearchController>(
                      id: 'follow_btn',
                      builder: (_) => _buildFollowBtn(
                        text: item.followFlag == 1 ? '取关'.tr : '关注'.tr,
                        isOutline: item.followFlag == 1,
                        onPressed: () => _.handleFollow(index),
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        );
      },
    );
  }

  /// 关注按钮
  Widget _buildFollowBtn({
    required String text,
    bool isOutline = false,
    VoidCallback? onPressed,
  }) {
    Widget btn;
    if (isOutline) {
      btn = OutlinedButton(
        onPressed: onPressed,
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.all(0),
          side: const BorderSide(color: AppColors.danger, width: 1),
          foregroundColor: Colors.white,
          enableFeedback: true,
        ),
        child: Text(
          text,
          style: const TextStyle(color: AppColors.danger, fontSize: 12),
        ),
      );
    } else {
      btn = ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.all(0),
          backgroundColor: AppColors.danger,
          foregroundColor: Colors.white,
          enableFeedback: true,
        ),
        child: Text(
          text,
          style: const TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }

    return SizedBox(
      width: 62,
      height: 24,
      child: btn,
    );
  }
}
